// ignore_for_file: unnecessary_overrides, non_constant_identifier_names

import 'dart:collection';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:convert' as convert;
import 'package:verse_systems/commom/models/product_model.dart';
import 'package:verse_systems/commom/routers/routes_pages_name.dart';

import 'package:verse_systems/net/http_dio.dart';
import 'package:verse_systems/pages/authentication/authentication_control.dart';
import 'package:verse_systems/pages/home/home_state.dart';
import 'package:verse_systems/utils/account_util.dart';
import 'package:verse_systems/utils/loading.dart';
import 'package:verse_systems/widgets/alert.dart';

class HomeControl extends GetxController {
  MethodChannel eventChannel = const MethodChannel('open_native_camera');

  final HomeState state = HomeState();

  void getAppHomeInfoList() async {
    final String token = await AccountUtil.getUserToken();
    Map<String, dynamic> map = HashMap();
    map['token'] = token;

    Request.postCallback(
      HttpUrls.getHomeInfo,
      data: map,
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        if (result.status == 0) {
          final List product = (result.data["product"] as List).cast();
          state.title = result.data["button"];
          state.placard = result.data["announcement"];
          state.amount = result.data["quota"];
          state.notice = result.data["notice"];
          state.behavior = result.data["behavior"];
          state.borrow_id = result.data["borrow_id"];

          final auto = result.data["auto"];
          final prize = result.data["prize"];
          state.productInfoList =
              product.map((json) => ProductModel.fromJson(json)).toList();

          update();
          //用来表示是否自动首页的触发按钮
          if (auto == true) {
            jumpToAuthen();
          }
          //新增抽奖提示
          if (prize == true) {
            Alert.showAlert(
                title: "opporunity".tr,
                confirm: "confirm".tr,
                cancel: "cancel".tr,
                content: "sweepstakes".tr,
                onPressed: () {
                  Get.toNamed(RoutesPage.LuckyWheel);
                });
          }
        }
      },
      error: (err) {},
    );
  }

  jumpProductWeb({String? productID}) async {
    final String token = await AccountUtil.getUserToken();
    Map<String, dynamic> map = HashMap();
    map['token'] = token;
    map['id'] = productID;

    Request.postCallback(
      HttpUrls.getProductLink,
      data: map,
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        if (result.status == 0) {
          String productUrl = result.data["path"];
          if (await canLaunchUrl(Uri.parse(productUrl))) {
            await launchUrl(Uri.parse(productUrl));
          } else {
            throw 'Could not launch $productUrl';
          }
        }
      },
    );
  }

  jumpToAuthen() async {
    debugPrint("state.behavior--${state.behavior}");
    switch (state.behavior) {
      case "created": //调申请订单得到订单id->调获取下一个认证项确认要去哪个认证
        applyOrders();
        break;

      case "order": //进入订单订单详情页
        Get.toNamed(RoutesPage.OrderDetails,
                arguments: {"borrow_id": state.borrow_id})!
            .then((value) {
          getAppHomeInfoList();
        });
        break;
      case "quota": //进入确认额度
        Get.toNamed(RoutesPage.Certification,
                arguments: {"borrow_id": state.borrow_id})!
            .then((value) {
          getAppHomeInfoList();
        });
        break;
      case "certification": //进入额度确认流程
        if (state.borrow_id == null) {
          applyOrders();
        } else {
          Get.toNamed(RoutesPage.Certification,
                  arguments: {"borrow_id": state.borrow_id})!
              .then((value) {
            getAppHomeInfoList();
          });
        }
        break;
      default:
    }
  }

// 申请订单
  applyOrders() async {
    final String token = await AccountUtil.getUserToken();
    Map<String, dynamic> map = HashMap();
    map['token'] = token;
    map['ip'] = "192.168.1.1";

    Request.postCallback(
      HttpUrls.applyOrder,
      data: map,
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        debugPrint("applyOrders--$result");
        if (result.status == 0) {
          String borrowId = result.data["borrow_id"].toString();
          nextCertification(borrowId: borrowId);
          final apply = result.data["apply"];
          if (apply == true) {
            //采集
            uploadDeviceInfo(borrowId: borrowId);
            uploadAppList(borrowId: borrowId);
            if (Platform.isAndroid) {
              PermissionStatus permission = await Permission.contacts.request();
              if (permission == PermissionStatus.granted) {
                uploadAddressBook(borrowId: borrowId);
              }
            } else {
              uploadAddressBook(borrowId: borrowId);
            }
            if (Platform.isAndroid) {
              PermissionStatus permission = await Permission.sms.request();
              if (permission == PermissionStatus.granted) {
                uploadSMSInfo(borrowId: borrowId);
              }
              PermissionStatus phone = await Permission.phone.request();
              if (phone == PermissionStatus.granted) {
                uploadCallInfo(borrowId: borrowId);
              }
            }
          }
        } else {
          Loading.showError(result.msg);
        }
      },
    );
  }

  nextCertification({required String borrowId}) async {
    final String token = await AccountUtil.getUserToken();
    Map<String, dynamic> map = HashMap();
    map['token'] = token;
    map['borrow_id'] = borrowId;
    Request.postCallback(
      HttpUrls.nextCertification,
      data: map,
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        debugPrint("nextCertification--$result");
        if (result.status == 0) {
          String code = result.data["code"].toString();
          final next = result.data["next"];
          if (next == true) {
            //需要进入下一步
            switch (code) {
              case "status_identity": //身份证认证
                Get.toNamed(RoutesPage.Authentication,
                        arguments: {"borrow_id": borrowId})!
                    .then((value) {
                  getAppHomeInfoList();
                });
                break;
              case "status_basic_info": //基本信息
                Get.put(AuthenticationControl());
                Get.toNamed(RoutesPage.AuthenticationInfo,
                        arguments: {"borrow_id": borrowId})!
                    .then((value) {
                  getAppHomeInfoList();
                });
                break;
              case "status_bankbinding": //银行卡信息认证
                Get.put(AuthenticationControl());
                Get.toNamed(RoutesPage.AuthenticationBank,
                        arguments: {"borrow_id": borrowId})!
                    .then((value) {
                       debugPrint("返回了。。。");
                  getAppHomeInfoList();
                });
                break;
              default:
            }
          } else {
            // next 返回 false 时，说明已经没有需要认证的项目，此时应该调用「额度确认页简要数据」
            state.borrow_id = borrowId;
            Get.toNamed(RoutesPage.Certification,
                    arguments: {"borrow_id": borrowId})!
                .then((value) {
              debugPrint("返回了。。。");
              getAppHomeInfoList();
            });
          }
        } else {
          Loading.showError("please_wait_review".tr);
        }
      },
    );
  }

  //异步采集信息
  uploadAddressBook({required String borrowId}) async {
    final String token = await AccountUtil.getUserToken();
    eventChannel.invokeMethod("open_contact_address").then((value) {
      Map<String, dynamic> map = HashMap();
      if (Platform.isAndroid) {
        final String jsonArray = value["jsonArray"];
        final List json = convert.jsonDecode(jsonArray);
        map['address_book'] = json;
      } else {
        map = Map<String, dynamic>.from(value);
      }
      map['token'] = token;
      map['borrow_id'] = borrowId;
      Request.postCallback(
        HttpUrls.uploadAddressBook,
        data: map,
        success: (res) async {
          ResultData result = ResultData.fromJson(res.data);
          debugPrint("上传通讯录信息--$result---map--$map");
        },
      );
    });
  }

  uploadAppList({required String borrowId}) async {
    final String token = await AccountUtil.getUserToken();
    eventChannel.invokeMethod("open_appInfo").then((value) {
      List app = [];
      if (Platform.isAndroid) {
        final String jsonArray = value["jsonArray"];
        final List json = convert.jsonDecode(jsonArray);
        app = json;
      } else {
        app = value;
      }

      Map<String, dynamic> map = HashMap();
      map['token'] = token;
      map['borrow_id'] = borrowId;
      map['app'] = app;
      debugPrint("上传appInfo信息--$map");
      Request.postCallback(
        HttpUrls.uploadAppList,
        data: map,
        success: (res) async {
          ResultData result = ResultData.fromJson(res.data);
          debugPrint("上传安装app信息--$result");
        },
      );
    });
  }

  uploadDeviceInfo({required String borrowId}) async {
    final String token = await AccountUtil.getUserToken();
    eventChannel.invokeMethod("open_deviceInfo").then((value) {
      Map<String, dynamic> map = Map<String, dynamic>.from(value);
      map['token'] = token;
      map['borrow_id'] = borrowId;
      debugPrint("uploadDeviceInfo--上传设备信息--$map");
      Request.postCallback(
        HttpUrls.uploadDeviceInfo,
        data: map,
        success: (res) async {
          ResultData result = ResultData.fromJson(res.data);
          debugPrint("上传设备信息--$result");
        },
      );
    });
  }

  uploadSMSInfo({required String borrowId}) async {
    final String token = await AccountUtil.getUserToken();
    eventChannel.invokeMethod("open_smsInfo").then((value) {
      final String jsonArray = value["jsonArray"];
      final List json = convert.jsonDecode(jsonArray);
      debugPrint("uploadSMSInfo--上传短信--$json");
      Map<String, dynamic> map = HashMap();
      map['token'] = token;
      map['borrow_id'] = borrowId;
      map['sms'] = json;
      Request.postCallback(
        HttpUrls.uploadSMSmInfo,
        data: map,
        success: (res) async {
          ResultData result = ResultData.fromJson(res.data);
          debugPrint("uploadSMSInfo--上传短信--$result-map--$map");
        },
      );
    });
  }

  uploadCallInfo({required String borrowId}) async {
    final String token = await AccountUtil.getUserToken();
    eventChannel.invokeMethod("open_callHistory").then((value) {
      final String jsonArray = value["jsonArray"];
      final List json = convert.jsonDecode(jsonArray);
      debugPrint("上传通话记录--$json");
      Map<String, dynamic> map = HashMap();
      map['token'] = token;
      map['borrow_id'] = borrowId;
      map['call_history'] = json;
      Request.postCallback(
        HttpUrls.uploadCallInfo,
        data: map,
        success: (res) async {
          ResultData result = ResultData.fromJson(res.data);
          debugPrint("uploadCallInfo--上传通话记录--$result-map--$map");
        },
      );
    });
  }

  @override
  void onInit() async {
    super.onInit();
  }
}
